package controllers

import (
	"beday20/models"
	beego "github.com/beego/beego/v2/server/web"
)

type ShopController struct {
	beego.Controller
}

func (c *ShopController) List() {

	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")

	var shop []models.Shop

	models.DB.Debug().Find(&shop)
	c.Data["json"] = Res{
		Code:    200,
		Data:    shop,
		Message: "展示成功",
	}
	c.ServeJSON()
	return
}

func (c *ShopController) Del() {
	id, _ := c.GetInt("id")

	models.DB.Debug().Delete(&models.Shop{}, id)
	c.Data["json"] = Res{
		Code:    200,
		Data:    nil,
		Message: "删除成功",
	}
	c.ServeJSON()
	return
}

func (c *ShopController) Add() {
	name := c.GetString("name")
	price, _ := c.GetFloat("price")
	time := c.GetString("time")
	num, _ := c.GetInt("num")
	status := c.GetString("status")
	author := c.GetString("author")

	if name == "" || price == 0 || num == 0 || status == "" || author == "" {
		c.Data["json"] = Res{
			Code:    500,
			Data:    nil,
			Message: "内容不能为空",
		}
		c.ServeJSON()
		return
	}

	shop := models.Shop{
		Name:   name,
		Price:  price,
		Time:   time,
		Num:    num,
		Status: status,
		Author: author,
	}

	models.DB.Debug().Create(&shop)
	c.Data["json"] = Res{
		Code:    200,
		Data:    shop,
		Message: "添加成功",
	}
	c.ServeJSON()
	return
}
